package cn.hg.solon.youcan.system.provider;

import static cn.hg.solon.youcan.system.entity.table.SysPositionTableDef.SYS_POSITION;

import java.util.Map;

import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryColumn;
import com.mybatisflex.core.query.QueryOrderBy;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;

import cn.hg.solon.youcan.common.constant.AppConstants;
import cn.hg.solon.youcan.common.exception.ServiceException;
import cn.hg.solon.youcan.system.entity.SysPosition;
import cn.hg.solon.youcan.system.mapper.SysPositionMapper;
import cn.hg.solon.youcan.system.service.SysPositionService;

/**
 * @author 胡高
 */
@Component
public class SysPositionProvider extends ServiceImpl<SysPositionMapper, SysPosition> implements SysPositionService {

    @Override
    public boolean checkUnique(SysPosition bean) {
        // 查找已存在记录
        QueryWrapper query = QueryWrapper.create()
            .where(SYS_POSITION.CODE.eq(bean.getCode())
                .and(SYS_POSITION.ID.ne(bean.getId()))
            );

        return ObjUtil.isNull(this.getOne(query));
    }

    @Override
    @Tran
    public Page<SysPosition> pageByMap(Page<SysPosition> page, Map<String, Object> map) {
        String status = (String)map.get("status");
        String word = (String)map.get("word");
        String sortField = (String)map.get("sortField");
        String sortType = (String)map.get("sortType");
        QueryWrapper query = QueryWrapper.create()
            .where(SYS_POSITION.STATUS.eq(status).when(StrValidator.isNotBlank(status))
                .and(SYS_POSITION.NAME.like(word).when(StrValidator.isNotBlank(word))
                    .or(SYS_POSITION.CODE.like(word).when(StrValidator.isNotBlank(word)))
                )
            );

        if (StrValidator.isNotBlank(sortField) && StrValidator.isNotBlank(sortType)) {
            query.orderBy(new QueryOrderBy(new QueryColumn(CharSequenceUtil.toUnderlineCase(sortField)), sortType));
        }

        return this.page(page, query);
    }

    @Override
    @Tran
    public boolean save(SysPosition bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "参数代码已经存在，请更换其它值！");
        }

        return super.save(bean);
    }

    @Override
    public boolean update(SysPosition bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "参数代码已经存在，请更换其它值！");
        }

        return this.updateById(bean);
    }

}
